import { Descriptions, DescriptionsProps } from 'antd';
import { useMemo } from 'react';

type EmptyValue =
  | undefined
  | null
  | ''
  | typeof NaN
  | []
  | Record<string, never>;

export function isEmptyValue(value: any): value is EmptyValue {
  if (
    value === undefined ||
    value === null ||
    value === '' ||
    Number.isNaN(value) ||
    (Array.isArray(value) && value.length <= 0) ||
    (typeof value === 'object' &&
      value !== null &&
      Object.keys(value).length <= 0)
  ) {
    return true;
  }
  return false;
}

export function convertEmptyToDash(value: any): string {
  return isEmptyValue(value) ? '-' : value;
}

/**
 *
 * @param 用法和普通的 antd Descriptions 一样，只是自动将空结果处理成 -
 * @param 空数组和空对象会处理成 -
 * @returns
 */
interface Props extends DescriptionsProps {
  children: any;
}
const Index = (props: Props) => {
  const { items, children } = props;

  const list = useMemo(() => {
    if (!items) return [];
    if (!Array.isArray(items)) return [];
    const arr: any[] = [];
    items.forEach((i: any, index: number) => {
      if (i) {
        arr.push({
          ...i,
          key: index,
          children: convertEmptyToDash(i?.children),
        });
      }
    });
    return arr;
  }, [items]);

  return (
    <Descriptions column={2} colon={false} {...props} items={list}>
      {children}
    </Descriptions>
  );
};
export default Index;
